package com.example.project.projectspringcloud.controller.front.user;

import com.example.project.projectspringcloud.common.Constants;
import com.example.project.projectspringcloud.common.OperationException;
import com.example.project.projectspringcloud.controller.BaseController;
import com.example.project.projectspringcloud.entity.Page;
import com.example.project.projectspringcloud.entity.RespBody;
import com.example.project.projectspringcloud.entity.sys.Dictionary;
import com.example.project.projectspringcloud.entity.user.Collect;
import com.example.project.projectspringcloud.entity.user.Evaluate;
import com.example.project.projectspringcloud.entity.user.Role;
import com.example.project.projectspringcloud.entity.user.User;
import com.example.project.projectspringcloud.entity.video.Video;
import com.example.project.projectspringcloud.service.sys.SysDictionaryService;
import com.example.project.projectspringcloud.service.user.UserCollectService;
import com.example.project.projectspringcloud.service.user.UserEvaluateService;
import com.example.project.projectspringcloud.service.user.UserService;
import com.example.project.projectspringcloud.service.video.VideoService;
import com.example.project.projectspringcloud.utils.RedisUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 用户Controller
 */
@Api(tags = "用户控制器")
@Controller
@RequestMapping(value = "/user")
public class UserController extends BaseController {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private UserService userService;

    @Autowired
    private VideoService videoService;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private SysDictionaryService sysDictionaryService;

    @Autowired
    private UserEvaluateService userEvaluateService;

    @Autowired
    private UserCollectService userCollectService;

    @ApiOperation(value = "用户详情", notes = "获取用户详情")
    @GetMapping(value = "/detail/{id}")
    public String detail(@PathVariable("id") Integer id, Model model) throws Exception {
        if (id != null) {
            User user = new User();
            user.setId(id);
            user.setCollectUser(super.getCurrentUserId());
            user = userService.getWithPrivate(user);
            if (user == null) {
                return "redirect:/404";
            }
            // 判断当前人是否有权限查看该信息
            for (Role role : user.getRoles()) {
                if (!
                        (Constants.UserRole.ROLE_PHOTOGRAPHER.toString().equals(role.getName())
                                || Constants.UserRole.ROLE_SCRIPTWRITER.toString().equals(role.getName()))) {
                    return "redirect:/403";
                }
            }
            model.addAttribute("user", user);

            if (super.getCurrentUser() != null) {
                // 获取当前登录用户收藏的摄影师/编剧列表
                List<Collect> collects = userCollectService.list(null, new Collect(getCurrentUser().getId(), 1));
                model.addAttribute("userCollects", collects);
            }

            // 获取该作者作品
            Video video = new Video();
            video.setAuthor(id);
            List<Video> videos = videoService.list(new Page(0, 8), video);
            model.addAttribute("videos", videos);

            if (getCurrentUser() != null) {
                // 获取收藏的作品
                List<Collect> collects = userCollectService.list(null, new Collect(getCurrentUser().getId(), 2));
                model.addAttribute("productionCollects", collects);
            }

            // 获取对摄影师/编剧的评价
            List<Evaluate> evaluates = userEvaluateService.list(null, new Evaluate(user.getId(), user.getType()));
            model.addAttribute("evaluatesPage", new Page<Evaluate>(evaluates));

            // 获取评价标签字典
            List<Dictionary> evaluateDictionaries = sysDictionaryService.list(new Dictionary(user.getType().equals(4) ? "evaluate-script-writer-tags" : "evaluate-photo-grapher-tags"), null);
            model.addAttribute("evaluateDictionaries", evaluateDictionaries);

            // 获取用户类型字典
            List<Dictionary> dictionaries = sysDictionaryService.list(new Dictionary("user-type"), null);
            model.addAttribute("dictionaries", dictionaries);

        }
        return isMobile() ? "m/content/production/user-detail" : "content/production/user-detail";
    }


    @ApiOperation(value = "API保存用户信息", notes = "根据ID判断是否存在, 执行是否更新/插入")
    @PostMapping(value = "/api/save")
    @ResponseBody
    public RespBody save(@Validated User user, BindingResult bindingResult) throws Exception {
        try {
            if (bindingResult.getErrorCount() > 0) {
                return RespBody.error(RespBody.ERROR_VALIDATE_CODE, super.translateI18N(bindingResult));
            }

            boolean result = userService.save(user);
            if (!result) {
                return RespBody.error(Constants.Message.SAVE_FAILED);
            }
        } catch (OperationException e) {
            return RespBody.error(e.getMessage());
        }

        return RespBody.ok(Constants.Message.SAVE_SUCCESS);
    }

    @ApiOperation(value = "API用户列表", notes = "获取api用户列表")
    @GetMapping(value = "/api/list")
    @ResponseBody
    public RespBody list(@ApiParam(name = "user", value = "用户对象") User user, Page page) throws Exception {
        user.setCollectUser(super.getCurrentUserId());
        if (user.getType().equals(4) || user.getType().equals(5)) {
            List<User> users = userService.list(page, user);
            return RespBody.ok(new Page<User>(users));
        } else {
            return null;
        }
    }

}
